// composables/useAxios.ts
import { ref } from "vue"
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios"
import { useCmConfigStore } from "../../store/baseStore"
import { useUserStore } from "../../store/userStore"
const axiosInstances: Record<string, AxiosInstance> = {}

// 封装请求函数，允许传入 instanceKey 动态选择 Axios 实例
export function useAxios<T>(
  config: AxiosRequestConfig,
  instanceKey: keyof typeof axiosInstances = "api1"
) {
  const data = ref<T | null>(null)
  const loading = ref<boolean>(false)
  const error = ref<string | null>(null)

  const fetchData = async () => {
    loading.value = true
    error.value = null
    try {
      // 根据传入的 instanceKey 获取对应的 Axios 实例
      const instance: AxiosInstance = axiosInstances[instanceKey]

      // 合并配置参数
      const mergedConfig: AxiosRequestConfig = {
        method: "POST", // 默认 POST 方法
        ...config,
      }

      const response: AxiosResponse<T> = await instance.request(mergedConfig)
      data.value = response.data
    } catch (err: any) {
      error.value = err.message || "请求失败"
    } finally {
      loading.value = false
    }
  }

  return { data, loading, error, fetchData }
}

export function initAxiosInstances(config) {
  for (let key in config) {
    const instance: AxiosInstance = (axiosInstances[key] = axios.create({
      baseURL: config[key],
      timeout: 10000,
      headers: {
        "Content-Type": "application/json",
      },
    }))

    // 添加请求拦截器
    instance.interceptors.request.use((config) => {
      // 在拦截器内部获取最新 Store 值
      const cmConfigStore = useCmConfigStore()
      const userStore = useUserStore()

      // 解构响应式属性（如果 merchantCompanyCode 是 ref）
      const { token } = userStore
      const { merchantCompanyCode } = cmConfigStore

      if (token) {
        config.headers.set("X-JWT", token)
      }
      // 添加请求头
      if (merchantCompanyCode) {
        config.headers.set("merchantcompanycode", merchantCompanyCode)
      }

      return config
    })
  }
}
